package com.youhome.controller;

import com.github.pagehelper.PageInfo;
import com.youhome.config.OSSConfig;
import com.youhome.model.BClient;
import com.youhome.model.BCounselor;
import com.youhome.response.Result;
import com.youhome.response.ResultPage;
import com.youhome.response.ResultCode;
import com.youhome.service.ClientService;
import com.youhome.service.CounselorService;
import com.youhome.service.UploadService;
import com.youhome.utils.DateUtils;
import com.youhome.utils.ValidationUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.Base64;
import java.util.Date;

/**
 * Created by chen365 on 2018/09/17.
 */
@Api(tags = "客户")
@RestController
@RequestMapping(value = "/clients")
public class ClientController {
    @Autowired
    private CounselorService counselorService;

    @Autowired
    private ClientService clientService;

    @Autowired
    private UploadService uploadService;

    @Autowired
    private OSSConfig ossConfig;

    public static void main(String[] args) {
        try {
            final Base64.Decoder decoder = Base64.getDecoder();
            final Base64.Encoder encoder = Base64.getEncoder();
            final String text = "字串文字";
            final byte[] textByte = text.getBytes("UTF-8");
            //编码
            final String encodedText = encoder.encodeToString(textByte);
            System.out.println(encodedText);
            //解码
            System.out.println(new String(decoder.decode(encodedText), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    @ApiOperation(value = "列表", notes = "列表", response = BClient.class, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "int", name = "pageNumber", value = "当前页码", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "int", name = "pageSize", value = "每页条数", required = false, paramType = "query")
    })
    @GetMapping(value = "")
    public Object list(HttpServletRequest request, Integer pageNumber, Integer pageSize) {
        BClient record = new BClient();
        BCounselor bCounselor = counselorService.selectByToken(request);
        System.err.println(bCounselor.toString());
        if (bCounselor != null) {
            record.setCounselorId(bCounselor.getCounselorId());
        }
        PageInfo<BClient> bClientPageInfo = clientService.selectByBean(pageNumber, pageSize, record);
        for (BClient client : bClientPageInfo.getList()) {
            if (!StringUtils.isEmpty(client.getPhoto())) {
                client.setPhoto(ossConfig.getDomain() + client.getPhoto());
            }
        }
        return new ResultPage<>(ResultCode.SUCCESS, bClientPageInfo);
    }

    @ApiOperation(value = "详情", notes = "详情", response = BCounselor.class, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "Long", name = "clientId", value = "客户ID", required = true, paramType = "path")
    })
    @GetMapping(value = "/{clientId}")
    public Object details(@PathVariable Long clientId) {
        if (StringUtils.isEmpty(clientId)) {
            return new Result<>(ResultCode.EMPTY_PARAMETER);
        }
        BClient bClient = clientService.selectByPrimaryKey(clientId);

        if (bClient == null) {
            return new Result<>(ResultCode.DATA_DOES_NOT_EXIST);
        }

        if (!StringUtils.isEmpty(bClient.getPhoto())) {
            bClient.setPhoto(ossConfig.getDomain() + bClient.getPhoto());
        }
        return new Result<>(ResultCode.SUCCESS, bClient);
    }

    @ApiOperation(value = "新增", notes = "新增", response = BClient.class, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "String", name = "name", value = "客户姓名", required = true, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "phone", value = "客户手机", required = true, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "weixin", value = "微信", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "qq", value = "QQ", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "investmentObjective", value = "投资目的(长期持有,自住,增值投资,租金收益,儿女留学居住)", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "capitalSource", value = "资金来源(国内资金，海外资金)", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "tendencyRoom", value = "房型倾向(独栋别墅,联排别墅,公寓)", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "tendencySite", value = "地点倾向", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "tendencyPrice", value = "价格倾向(100万人民币以内,100-200万人民币,200-400万人民币,400-700万人民币,700-1000万人民币,1000万人民币以上)", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "tendencySize", value = "面积倾向(100平米以内,150平米以内,200平米以内,250平米以内,300平米以内,400平米以内,500平米以内,500平米以上)", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "tendencySchool", value = "学校评分倾向（1~5,5~7,8~10）", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "province", value = "省(州)", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "city", value = "市(区)", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "area", value = "区(县)", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "address", value = "详细地址", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "birthDate", value = "出生年月日(格式：yyyy-MM-dd)", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "int", name = "marital", value = "婚姻，0保密，1已婚，2未婚，3离异", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "income", value = "年收入", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "jobTitle", value = "职称", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "jobType", value = "工作行业", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "int", name = "gender", value = "性别，0女，1男", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "int", name = "email", value = "邮箱", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "photo", value = "头像地址", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "remark", value = "备注", required = false, paramType = "query")
    })
    @PostMapping(value = "")
    public Object add(HttpServletRequest request, String name, String phone, String weixin, String qq, String investmentObjective,
                      String capitalSource, String tendencyRoom, String tendencySite, String tendencyPrice,
                      String tendencySize, String tendencySchool, String province, String city, String area,
                      String address, String birthDate, Integer marital, String income, String jobTitle, String jobType,
                      Integer gender, String email, String photo, String remark) {

        BCounselor bCounselor = counselorService.selectByToken(request);
        if (bCounselor == null) {
            return new Result<>(ResultCode.LAND_EXPIRATION);
        }

        BClient bClient = new BClient();
        bClient.setCounselorId(bCounselor.getCounselorId()); //顾问ID
        bClient.setCompanyId(bCounselor.getCompanyId()); //公司ID

        if (StringUtils.isEmpty(name)) {
            return new Result<>(ResultCode.EMPTY_NAME);
        }
        bClient.setName(name);
        if (StringUtils.isEmpty(phone)) {
            return new Result<>(ResultCode.EMPTY_PHOTO);
        }
        bClient.setPhone(phone);
        if (!StringUtils.isEmpty(weixin)) {
            bClient.setWeixin(weixin);
        }
        if (!StringUtils.isEmpty(qq)) {
            bClient.setQq(qq);
        }
        if (!StringUtils.isEmpty(investmentObjective)) {
            bClient.setInvestmentObjective(investmentObjective);
        }
        if (!StringUtils.isEmpty(capitalSource)) {
            bClient.setCapitalSource(capitalSource);
        }
        if (!StringUtils.isEmpty(tendencyRoom)) {
            bClient.setTendencyRoom(tendencyRoom);
        }
        if (!StringUtils.isEmpty(tendencySite)) {
            bClient.setTendencySite(tendencySite);
        }
        if (!StringUtils.isEmpty(tendencyPrice)) {
            bClient.setTendencyPrice(tendencyPrice);
        }
        if (!StringUtils.isEmpty(tendencySize)) {
            bClient.setTendencySize(tendencySize);
        }
        if (!StringUtils.isEmpty(tendencySchool)) {
            bClient.setTendencySchool(tendencySchool);
        }
        if (!StringUtils.isEmpty(province)) {
            bClient.setProvince(province);
        }
        if (!StringUtils.isEmpty(city)) {
            bClient.setCity(city);
        }
        if (!StringUtils.isEmpty(area)) {
            bClient.setArea(area);
        }
        if (!StringUtils.isEmpty(address)) {
            bClient.setAddress(address);
        }
        if (!StringUtils.isEmpty(birthDate)) {
            bClient.setBirthdate(DateUtils.stringToDate(birthDate, "yyyy-MM-dd"));
        }
        if (!StringUtils.isEmpty(marital)) {
            bClient.setMarital(marital);
        }
        if (!StringUtils.isEmpty(income)) {
            bClient.setIncome(income);
        }
        if (!StringUtils.isEmpty(jobTitle)) {
            bClient.setJobTitle(jobTitle);
        }
        if (!StringUtils.isEmpty(jobType)) {
            bClient.setJobType(jobType);
        }
        if (!StringUtils.isEmpty(gender)) {
            bClient.setSex(gender);
        }
        if (!StringUtils.isEmpty(email)) {
            bClient.setEmail(email);
        }
        if (!StringUtils.isEmpty(photo)) {
            System.err.println("photo:" + photo);
            System.err.println("domain:" + ossConfig.getDomain());
            photo = photo.replaceAll(ossConfig.getDomain(), ""); //去掉 oss url
            System.err.println("photo:" + photo);
            bClient.setPhoto(photo);
        }
        if (!StringUtils.isEmpty(remark)) {
            bClient.setRemark(remark);
        }

        int success = clientService.insert(bClient);
        if (success > 0) {
            return new Result<>(ResultCode.SUCCESS);
        }

        return new Result<>(ResultCode.FAIL);
    }

    @ApiOperation(value = "修改", notes = "修改", response = Result.class, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "Long", name = "clientId", value = "客户ID", required = true, paramType = "path"),
            @ApiImplicitParam(dataType = "String", name = "name", value = "客户姓名", required = true, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "phone", value = "客户手机", required = true, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "weixin", value = "微信", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "qq", value = "QQ", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "investmentObjective", value = "投资目的(长期持有,自住,增值投资,租金收益,儿女留学居住)", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "capitalSource", value = "资金来源(国内资金，海外资金)", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "tendencyRoom", value = "房型倾向(独栋别墅,联排别墅,公寓)", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "tendencySite", value = "地点倾向", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "tendencyPrice", value = "价格倾向(100万人民币以内,100-200万人民币,200-400万人民币,400-700万人民币,700-1000万人民币,1000万人民币以上)", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "tendencySize", value = "面积倾向(100平米以内,150平米以内,200平米以内,250平米以内,300平米以内,400平米以内,500平米以内,500平米以上)", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "tendencySchool", value = "学校评分倾向（1~5,5~7,8~10）", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "province", value = "省(州)", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "city", value = "市(区)", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "area", value = "区(县)", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "address", value = "详细地址", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "birthDate", value = "出生年月日(yyyy-MM-dd)", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "int", name = "marital", value = "婚姻，0保密，1已婚，2未婚，3离异", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "income", value = "年收入", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "jobTitle", value = "职称", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "jobType", value = "工作行业", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "int", name = "gender", value = "性别，0女，1男", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "int", name = "email", value = "邮箱", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "photo", value = "头像地址", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "remark", value = "备注", required = false, paramType = "query")
    })
    @PutMapping(value = "/{clientId}")
    public Object update(HttpServletRequest request, @PathVariable Long clientId, String name, String phone, String weixin, String qq, String investmentObjective,
                         String capitalSource, String tendencyRoom, String tendencySite, String tendencyPrice,
                         String tendencySize, String tendencySchool, String province, String city, String area,
                         String address, String birthDate, Integer marital, String income, String jobTitle, String jobType,
                         Integer gender, String email, String photo, String remark) {

        BCounselor bCounselor = counselorService.selectByToken(request);
        if (bCounselor == null) {
            return new Result<>(ResultCode.LAND_EXPIRATION);
        }

        BClient bClient = new BClient();
        bClient.setClientId(clientId); //客户ID
        bClient.setCounselorId(bCounselor.getCounselorId()); //顾问ID
        bClient.setCompanyId(bCounselor.getCompanyId()); //公司ID

        if (StringUtils.isEmpty(name)) {
            return new Result<>(ResultCode.EMPTY_NAME);
        }
        bClient.setName(name);
        if (StringUtils.isEmpty(phone)) {
            return new Result<>(ResultCode.EMPTY_PHOTO);
        }
        bClient.setPhone(phone);
        if (!StringUtils.isEmpty(weixin)) {
            bClient.setWeixin(weixin);
        }
        if (!StringUtils.isEmpty(qq)) {
            bClient.setQq(qq);
        }
        if (!StringUtils.isEmpty(investmentObjective)) {
            bClient.setInvestmentObjective(investmentObjective);
        }
        if (!StringUtils.isEmpty(capitalSource)) {
            bClient.setCapitalSource(capitalSource);
        }
        if (!StringUtils.isEmpty(tendencyRoom)) {
            bClient.setTendencyRoom(tendencyRoom);
        }
        if (!StringUtils.isEmpty(tendencySite)) {
            bClient.setTendencySite(tendencySite);
        }
        if (!StringUtils.isEmpty(tendencyPrice)) {
            bClient.setTendencyPrice(tendencyPrice);
        }
        if (!StringUtils.isEmpty(tendencySize)) {
            bClient.setTendencySize(tendencySize);
        }
        if (!StringUtils.isEmpty(tendencySchool)) {
            bClient.setTendencySchool(tendencySchool);
        }
        if (!StringUtils.isEmpty(province)) {
            bClient.setProvince(province);
        }
        if (!StringUtils.isEmpty(city)) {
            bClient.setCity(city);
        }
        if (!StringUtils.isEmpty(area)) {
            bClient.setArea(area);
        }
        if (!StringUtils.isEmpty(address)) {
            bClient.setAddress(address);
        }
        if (!StringUtils.isEmpty(birthDate)) {
            bClient.setBirthdate(DateUtils.stringToDate(birthDate, "yyyy-MM-dd"));
        }
        if (!StringUtils.isEmpty(marital)) {
            bClient.setMarital(marital);
        }
        if (!StringUtils.isEmpty(income)) {
            bClient.setIncome(income);
        }
        if (!StringUtils.isEmpty(jobTitle)) {
            bClient.setJobTitle(jobTitle);
        }
        if (!StringUtils.isEmpty(jobType)) {
            bClient.setJobType(jobType);
        }
        if (!StringUtils.isEmpty(gender)) {
            bClient.setSex(gender);
        }
        if (!StringUtils.isEmpty(email)) {
            if (!ValidationUtils.isEmail(email)) {
                return new Result<>(ResultCode.ERROR_EMAIL_FORMAT);
            }
            bClient.setEmail(email);
        }
        if (!StringUtils.isEmpty(photo)) {
            photo = photo.replaceAll(ossConfig.getDomain(), ""); //去掉 oss url
            bClient.setPhoto(photo);
        }
        if (!StringUtils.isEmpty(remark)) {
            bClient.setRemark(remark);
        }

        int success = clientService.updateByClientIdAndCounselorId(bClient);
        if (success > 0) {
            return new Result<>(ResultCode.SUCCESS);
        }

        return new Result<>(ResultCode.FAIL);
    }

    @ApiOperation(value = "删除", notes = "删除", response = BCounselor.class, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "Long", name = "clientId", value = "客户ID", required = true, paramType = "path")
    })
    @DeleteMapping(value = "/{clientId}")
    public Object delete(HttpServletRequest request, @PathVariable Long clientId) {
        if (StringUtils.isEmpty(clientId)) {
            return new Result<>(ResultCode.EMPTY_PARAMETER);
        }
        BCounselor bCounselor = counselorService.selectByToken(request);
        if (bCounselor == null) {
            return new Result<>(ResultCode.LAND_EXPIRATION);
        }

        BClient bClient = new BClient();
        bClient.setClientId(clientId); //客户ID
        bClient.setCounselorId(bCounselor.getCounselorId()); //顾问ID

        if (clientService.deleteByClientIdAndCounselorId(bClient) > 0) {
            return new Result<>(ResultCode.SUCCESS);
        }

        return new Result<>(ResultCode.FAIL);
    }

//    @ApiOperation(value = "上传头像", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
//    @PostMapping(value = "/photo/upload")
//    public Object uploadPhoto(@RequestParam("myFile") MultipartFile myFile) {
//        Integer type = 2; // 1:upload,2:photo,3:house,4:company
//        String imageUrl = uploadService.upload(myFile, type);
//        System.err.println("imageUrl:" + imageUrl);
//        if (!StringUtils.isEmpty(imageUrl)) {
//            imageUrl = ossConfig.getDomain() + "/" + imageUrl;
//            return new Result(ResultCode.SUCCESS, imageUrl);
//        } else {
//            return new Result(ResultCode.FAIL);
//        }
//    }

    @ApiOperation(value = "上传头像", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "String", name = "data", value = "base64 数据", required = true, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "ext", value = "图片后辍名(jpg,png)", required = true, paramType = "query")
    })
    @PostMapping(value = "/photo/upload")
    public Object uploadPhoto(String data, String ext) {
        if (StringUtils.isEmpty(data)) {
            return new Result<>(ResultCode.EMPTY_BASE64_DATA);
        }
        if (StringUtils.isEmpty(ext)) {
            return new Result<>(ResultCode.EMPTY_IMG_SUFFIX);
        }
        try {
            String upload = uploadService.upload(data, ext);
            if (!StringUtils.isEmpty(upload)) {
                return new Result<>(ResultCode.SUCCESS, upload);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new Result<>(ResultCode.FAIL.getStatus(), e.getMessage());
        }
        return new Result<>(ResultCode.FAIL);
    }
}
